package com.cat.model.biz.service.api.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alonew.core.commons.tuple.TwoTuple;
import com.alonew.core.commons.util.secure.MD5Util;
import com.alonew.db.dao.TxCommonDAO;
import com.alonew.json.JSONException;
import com.alonew.json.JSONObject;
import com.cat.model.biz.service.api.UserService;
import com.cat.model.biz.service.bs.UserBS;
import com.cat.model.common.model.common.CompanyInfoVO;
import com.cat.model.common.model.common.SuggestionVO;
import com.cat.model.common.model.common.UserAuthInfoVO;
import com.cat.model.common.model.common.UserInfoVO;
import com.cat.model.common.model.common.UserPhoneVO;
import com.cat.model.common.util.ErrorCode;
import com.cat.model.common.util.FileUtil;
import com.cat.model.common.util.ImageUtil;
import com.cat.model.common.util.StaticFileUtil;
import com.cat.model.dao.mapper.ModelMapper;
import com.cat.model.dao.mapper.UserInfoMapper;
import com.cat.model.web.bean.CompanyInfoBean;

@Service("userService")
public class UserServiceImpl implements UserService{
	
	@Autowired
	UserBS userBS;
	
	@Autowired
	UserInfoMapper userMapper;
	
	@Autowired
	ModelMapper modelMapper;

	@Autowired
	private TxCommonDAO txCommonDAO;
	@Override
	public String userInfo(long userId) {
		UserInfoVO userInfo = userMapper.getUserInfo(userId);
		if(null == userInfo){
			return ErrorCode.OK.response();
		}
		
		UserPhoneVO userPhone = userMapper.getUserPhoneByUserId(userId);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			JSONObject infoJson = new JSONObject();
			infoJson.put("nickName", userInfo.getNickName());
			infoJson.put("realName", userInfo.getRealName());
			infoJson.put("inviterId", userInfo.getInviterId());
			infoJson.put("headImage", ImageUtil.wrapImageUrl(userInfo.getHeadImage()));
			if(userPhone != null){
				infoJson.put("phoneNo", userPhone.getPhoneNo());
			}
			infoJson.put("userLevel", userInfo.getUserLevel());
			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		
		return json.toString();
	}
	
	@Override
	public String updateNickName(long userId, String nickName) {
		userBS.updateNickName(userId, nickName);
		return ErrorCode.OK.response();
	}
	
	@Override
	public String updateRealName(long userId, String realName) {
		userBS.updateRealName(userId, realName);
		return ErrorCode.OK.response();
	}

	@Override
	public String updateHeadImage(long userId,  File headImage, String headImageFileName) {
		String headImagePath = "";
		if(headImage != null){
			String imagePath = StaticFileUtil.userRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(headImage);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, headImageFileName, md5AndData.second);
			headImagePath = imagePath + "/" + headImageFileName;
		}
		
		userBS.updateHeadImage(userId, headImagePath);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			JSONObject infoJson = new JSONObject();
			infoJson.put("headImage", ImageUtil.wrapImageUrl(headImagePath));			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		return json.toString();
	}

	@Override
	public String updatePassword(long userId, String oldPassword, String password) {
		UserInfoVO userInfo = userMapper.getUserInfo(userId);
		if(null == userInfo || !MD5Util.encode(oldPassword).equals(userInfo.getPassword())){
			return ErrorCode.PASSWORD_ERROR.response();
		}
		
		userBS.updatePassword(userId, password);
		return ErrorCode.OK.response();
	}

	@Override
	public String userAuthInfo(long userId) {
		UserInfoVO userInfo = userMapper.getUserInfo(userId);
		JSONObject infoJson = new JSONObject();

		if(null == userInfo){
			UserAuthInfoVO userAuthInfo = new UserAuthInfoVO();
			userAuthInfo.setApproveStatus("00");
			try {
				infoJson.put("userAuthInfo", JSONObject.wrap(userAuthInfo));
			} catch (JSONException e) {
				return ErrorCode.SERVER_ERROR.response();
			}
			return ErrorCode.OK.response();
		}
		
		UserAuthInfoVO userAuthInfo = modelMapper.getUserAuthInfoByUserId(userId);
		if(userAuthInfo==null){
			return ErrorCode.OK.response();
		}
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			userAuthInfo.setBusinessLicense(ImageUtil.wrapImageUrl(userAuthInfo.getBusinessLicense()));
			userAuthInfo.setIdCardBack(ImageUtil.wrapImageUrl(userAuthInfo.getIdCardBack()));
			userAuthInfo.setIdCardPositive(ImageUtil.wrapImageUrl(userAuthInfo.getIdCardPositive()));
			infoJson.put("userAuthInfo", JSONObject.wrap(userAuthInfo));
			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		
		return json.toString();
	}

	@Override
	public String updateUserAuthInfo(long userId, File businessLicense,String businessLicenseFileName) {
		String businessLicensePath = "";
		if(businessLicense != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(businessLicense);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, businessLicenseFileName, md5AndData.second);
			businessLicensePath = imagePath + "/" + businessLicenseFileName;
		}
		
		userBS.updateBusinessLicense(userId, businessLicensePath);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			JSONObject infoJson = new JSONObject();
			infoJson.put("businessLicense", ImageUtil.wrapImageUrl(businessLicensePath));			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		return json.toString();
	}
	
	
	
	/**
	 * 保存认证信息
	 */
	public String saveUserAuthInfo(long userId, File businessLicense, String businessLicenseFileName
			,File idCardPositive,String idCardPositiveFileName,String name,String phone,Integer type,String businessLicenseNumber,String addr){
		
		
		UserAuthInfoVO userAuthInfo = modelMapper.getUserAuthInfoByUserId(userId);
		if(userAuthInfo!=null){
			if("03".equals(userAuthInfo.getApproveStatus())){
				return ErrorCode.app_STATUS_ERROR.response();
			}else{
				modelMapper.deleteUserAuthInfoByUserId(userId);
			}
		}
		
		String businessLicensePath = "";
		String idCardPositivePath = "";
		if(businessLicense != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(businessLicense);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, businessLicenseFileName, md5AndData.second);
			businessLicensePath = imagePath + "/" + businessLicenseFileName;
		}
		if(idCardPositive != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(idCardPositive);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, idCardPositiveFileName, md5AndData.second);
			idCardPositivePath = imagePath + "/" + idCardPositiveFileName;
		}
		UserAuthInfoVO userAuthInfoVO=new UserAuthInfoVO();
		userAuthInfoVO.setBusinessLicense(businessLicensePath);
		userAuthInfoVO.setApplyTime(new Date());
		userAuthInfoVO.setApproveStatus("01");//待审核
		userAuthInfoVO.setAuthType(1);
		userAuthInfoVO.setUserId(userId);
		
		userAuthInfoVO.setAddr(addr);
		userAuthInfoVO.setIdCardPositive(idCardPositivePath);
		userAuthInfoVO.setBusinessLicenseNumber(businessLicenseNumber);
		userAuthInfoVO.setName(name);
		userAuthInfoVO.setPhone(phone);
		userAuthInfoVO.setType(type);
		txCommonDAO.insert(userAuthInfoVO);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		/*try {
			JSONObject infoJson = new JSONObject();
			infoJson.put("businessLicense", ImageUtil.wrapImageUrl(businessLicensePath));			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}*/
		return json.toString();
	}
	
	/**
	 * 保存个人认证信息
	 */
	public	String savePersonUserAuthInfo(long userId, File idCardPositive, String idCardPositiveFileName
			, File idCardBack, String idCardBackFileName
			,String name,String phone,Integer type,String BusinessLicenseNumber,String addr){
		

		UserAuthInfoVO userAuthInfo = modelMapper.getUserAuthInfoByUserId(userId);
		if(userAuthInfo!=null){
			if("03".equals(userAuthInfo.getApproveStatus())){
				return ErrorCode.app_STATUS_ERROR.response();
			}else{
				modelMapper.deleteUserAuthInfoByUserId(userId);
			}
		}
		
		String idCardPositivePath = "";
		if(idCardPositive != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(idCardPositive);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, idCardPositiveFileName, md5AndData.second);
			idCardPositivePath = imagePath + "/" + idCardPositiveFileName;
		}
		
		String idCardBackPath = "";
		if(idCardBack != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(idCardBack);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, idCardBackFileName, md5AndData.second);
			idCardBackPath = imagePath + "/" + idCardBackFileName;
		}
		
		UserAuthInfoVO userAuthInfoVO=new UserAuthInfoVO();
		userAuthInfoVO.setIdCardPositive(idCardPositivePath);
		userAuthInfoVO.setIdCardBack(idCardBackPath);
		userAuthInfoVO.setApplyTime(new Date());
		userAuthInfoVO.setApproveStatus("01");//待审核
		userAuthInfoVO.setAuthType(2);//个人
		userAuthInfoVO.setUserId(userId);
		
		userAuthInfoVO.setAddr(addr);
		userAuthInfoVO.setName(name);
		userAuthInfoVO.setPhone(phone);
		userAuthInfoVO.setType(type);
		txCommonDAO.insert(userAuthInfoVO);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		/*try {
			JSONObject infoJson = new JSONObject();
			infoJson.put("businessLicense", ImageUtil.wrapImageUrl(businessLicensePath));			
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}*/
		return json.toString();
		
	}
	
	
	@Override
	public String updateEmployeeAuthInfo(long userId, File idCardPositive,String idCardPositiveFileName, File idCardBack,
			String idCardBackFileName, File idCardHolder,String idCardHolderFileName) {
		String idCardPositivePath = "";
		if(idCardPositive != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(idCardPositive);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, idCardPositiveFileName, md5AndData.second);
			idCardPositivePath = imagePath + "/" + idCardPositiveFileName;
		}
		String idCardBackPath = "";
		if(idCardPositive != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(idCardBack);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, idCardBackFileName, md5AndData.second);
			idCardBackPath = imagePath + "/" + idCardBackFileName;
		}
		String idCardHolderPath = "";
		if(idCardPositive != null){
			String imagePath = StaticFileUtil.userAuthInfoRelativePath() + FileUtil.buildDatePath();
			TwoTuple<String, byte[]> md5AndData = FileUtil.readAndCalMd5(idCardHolder);
			FileUtil.writeFile(StaticFileUtil.staticRootPath() + imagePath, idCardHolderFileName, md5AndData.second);
			idCardHolderPath = imagePath + "/" + idCardHolderFileName;
		}
		
		userBS.updateEmployeeAuthInfo(userId, idCardPositivePath,idCardBackPath,idCardHolderPath);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		try {
			JSONObject infoJson = new JSONObject();
			infoJson.put("idCardPositive", ImageUtil.wrapImageUrl(idCardPositivePath));		
			infoJson.put("idCardBack", ImageUtil.wrapImageUrl(idCardBackPath));		
			infoJson.put("idCardHolder", ImageUtil.wrapImageUrl(idCardHolderPath));		
			json.put("data", infoJson);
		} catch (JSONException e) {
			return ErrorCode.SERVER_ERROR.response();
		}
		return json.toString();
	}

	public String suggestion(long userId, String content){
		SuggestionVO suggestionVO=new SuggestionVO();
		suggestionVO.setContent(content);
		suggestionVO.setUserId(userId);
		txCommonDAO.insert(suggestionVO);
		
		JSONObject json = ErrorCode.OK.responseJSON();
		return json.toString();
	}
	
	public String getCompanyList(){
		JSONObject json = ErrorCode.OK.responseJSON();
		
		List<CompanyInfoVO> companyInfoList=modelMapper.getCompanyList();
		List<CompanyInfoBean> result=new ArrayList<CompanyInfoBean>();
		for (CompanyInfoVO companyInfoVO : companyInfoList) {
			CompanyInfoBean bean=new CompanyInfoBean();
			BeanUtils.copyProperties(companyInfoVO, bean);
			result.add(bean);
		}
		try {
			json.put("data", result);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			return ErrorCode.SERVER_ERROR.response();
		}
		return json.toString();
	}
}
